package com.k8.rpc.expoter;

import com.k8.common.event.Event;
import com.k8.common.event.EventDeployer;
import com.k8.rpc.url.ApiSignature;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

@Slf4j
public abstract class AbstractExporter<T> implements Exporter<T> {
    private ExecutorService executorService;
    private EventDeployer eventDeployer;
    private ApiSignature apiSignature;

    public AbstractExporter(ExecutorService executorService, EventDeployer eventDeployer, ApiSignature apiSignature) {
        assert executorService != null;
        assert eventDeployer != null;
        this.executorService = executorService;
        this.eventDeployer = eventDeployer;
    }

    @Override
    public final void register() {
        CompletableFuture<Void> registerFuture = CompletableFuture.runAsync(() -> {
            doRegister();
        }, executorService);
        //注册完成后发布事件
        registerFuture.whenComplete((value, exception) -> {
            Event event = new ExporterListener.ExporterEvent(apiSignature.getRegisterPath(), apiSignature.getPath(), exception);
            eventDeployer.publishEvent(event);
        });
    }

    protected abstract void doRegister();

}
